/**
 * Copyright (c) 2012 Nokia Corporation.
 * All rights reserved.
 *
 * For the applicable distribution terms see the license text file included in
 * the distribution.
 */

var graphUrl = "https://graph.facebook.com/";


/*!
  Helper function for updating places to model.
*/
function parseJSONtoModel(json)
{
    var i = 0;
    var jsonData = JSON.parse(json);
    placesListModel.updatePlacesData(jsonData.data);
}


/*!
  Gets data from JSON object.
*/
function getDataFromJSON(json, path)
{
    var value;
    var jsonData = JSON.parse(json);
    value = eval("jsonData." + path + ";");

    if (value === undefined) {
        value = "";
    }

    return value;
}


/*!
  Updates nearby places by current position.
*/
function updateNearbyPlaces()
{
    var parameters = {
        "distance": 1000,
        "limit": 25,
        "type": "place",
        "center": lastUpdatePos.latitude + "," + lastUpdatePos.longitude
    }

    fbConnect.request("getNearbyPlaces", "search", parameters);
}


/*!
  Process completed FBConnect request.
*/
function requestCompleted(requestId, result)
{
    switch (requestId) {
    case "getNearbyPlaces":
        parseJSONtoModel(result);
        break;
    default:
        break;
    }
}


/*!
  Process failed requests.
*/
function requestFailed(requestId, reason)
{
    // Note: End-of-line "\n" is a workaround for this bug:
    // https://bugreports.qt-project.org/browse/QTCOMPONENTS-1174
    errorDialog.message = qsTr(reason + "\n");
    errorDialog.open();
}


/*!
  Checks if updating places is needed.
*/
function checkForUpdate(forceUpdate)
{
    // Update if position has changed more than 400m, or update is forced.
    if (positionSource.position.coordinate.distanceTo(lastUpdatePos) > 400 || forceUpdate){
        lastUpdatePos.latitude = positionSource.position.coordinate.latitude;
        lastUpdatePos.longitude = positionSource.position.coordinate.longitude;
        updateNearbyPlaces();
    }
}


/*!
  Forces map view to be shown. Pops all other views from page stack.
*/
function showMap()
{
    pageStack.pop(placesMapPage);
    buttonRow.mapSelected = true;
    listViewVisible = false;
}
